<template>
  <div>
    <div style="margin-top: 10px">
      <el-form ref="form" :model="form" label-width="80px" class="">
        <el-form-item class="form-item" label="任务名称">
          <el-input v-model="form.name" placeholder="任务名称"></el-input>
        </el-form-item>
        <el-form-item class="form-item">
          <el-button class="form-btn" type="primary" @click="onQuery">查询</el-button>
          <el-button class="form-btn" @click="clearQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div><br/>
    <!--增改删导出-->
    <el-row>
      <el-button class="tag-btn" type="success" plain @click="clickAddItf">新增</el-button>
      <el-button class="tag-btn" type="warning" plain @click="modifyItf('modify')">修改</el-button>
      <el-button class="tag-btn" type="danger" plain @click="delItf('del')">删除</el-button>
      <el-button class="tag-btn" type="info" plain @click="outputItfData">导出</el-button>
      <template>
        <el-input-number class="curPageCounter" @change="handleCurrentChange" v-model="curPage" :min="1" :max="pages" label="描述文字"></el-input-number>
      </template>
    </el-row>

    <!--列表-->
    <template>
      <el-table
        class="interface-table"
        ref="multipleTable"
        :data="jobtableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column
          align="center"
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          align="center"
          prop="jobId"
          label="任务ID"
          width="140">
        </el-table-column>
        <el-table-column
          align="center"
          prop="jobName"
          label="任务名称"
          width="150">
        </el-table-column>
        <el-table-column
          align="center"
          prop="jobDesc"
          label="任务描述"
          width="200">
        </el-table-column>
        <el-table-column
          align="center"
          prop="groupId"
          label="任务组ID"
          width="80">
        </el-table-column>
        <el-table-column
          align="center"
          prop="beanName"
          label="任务运行类"
          width="220">
        </el-table-column>
        <el-table-column
          align="center"
          prop="cron"
          label="cron表达式"
          width="120">
        </el-table-column>
        <el-table-column
          align="center"
          prop="status"
          label="任务状态"
          width="100">
        </el-table-column>
        <el-table-column
          align="center"
          prop="createTime"
          label="创建时间"
          width="100">
        </el-table-column>
        <el-table-column
          align="center"
          label="操作">
          <template slot-scope="scope">
            <el-button
              v-show="scope.row.status==='OFF'"
              size="mini"
              type="success"
              @click="handleResume(scope.$index, scope.row)">恢复</el-button>
            <el-button
              v-show="scope.row.status==='ON'"
              size="mini"
              type="info"
              @click="handlePause(scope.$index, scope.row)">暂停</el-button>
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          background
          class="interpage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="curPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </template>
    <!--新增接口对话框-->
    <el-dialog
      title="新增定时任务"
      :visible.sync="addItfVisible"
      width="40%">
      <el-form label-width="100px" ref="addItfForm" :model="addItfForm" :rules="jobRules">
        <el-form-item label="任务ID">
          <el-input v-model="addItfForm.jobId" placeholder="任务ID" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="任务组">
          <el-select v-model="addItfForm.groupId" placeholder="任务组1">
            <el-option label="任务组1-GID001" value="GID001"></el-option>
            <el-option label="任务组2-GID002" value="GID002"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务名称">
          <el-input v-model="addItfForm.jobName" placeholder="任务名称"></el-input>
        </el-form-item>
        <el-form-item label="任务类型">
          <el-select v-model="addItfForm.jobType" placeholder="定时">
            <el-option label="定时-FIXTIME" value="FIXTIME"></el-option>
            <el-option label="实时-REALTIME" value="REALTIME"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="cron" v-if="addItfForm.jobType === 'FIXTIME' || addItfForm.jobType === ''" label="Cron表达式">
          <el-popover v-model="cronPopover">
              <cron @change="changeCron" @close="cronPopover=false" i18n="cn"></cron>
              <el-input slot="reference" @click="cronPopover=true" v-model="addItfForm.cron" placeholder="请点击选择定时策略"></el-input>
          </el-popover>
        </el-form-item>
        <el-form-item v-if="addItfForm.jobType === 'REALTIME'" label="Cron表达式">
          <el-input v-model="mTempCron" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item prop="beanName" label="任务执行类">
          <el-input v-model="addItfForm.beanName" placeholder="任务执行类"></el-input>
        </el-form-item>
        <el-form-item label="任务参数">
          <el-input v-model="addItfForm.jobParams" placeholder="任务参数，key=value结构，多个参数间逗号隔开"></el-input>
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input
            style="font-size: 16px;"
            type="textarea"
            :rows="5"
            placeholder='请输入任务描述'
            v-model="addItfForm.jobDesc">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addItfVisible = false">取 消</el-button>
        <el-button type="primary" @click="addItf">提交</el-button>
      </span>
    </el-dialog>

    <!--修改接口对话框-->
    <el-dialog
      title="修改定时任务"
      :visible.sync="modifyRoleVisible"
      width="40%">
      <el-form label-width="100px" ref="modifyRoleForm" :model="modifyRoleForm" :rules="mJobRules">
        <el-form-item label="任务ID">
          <el-input v-model="modifyRoleForm.jobId" placeholder="任务ID" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="任务组ID">
          <el-input v-model="modifyRoleForm.groupId" placeholder="任务组ID" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="任务名称">
          <el-input v-model="modifyRoleForm.jobName" placeholder="任务名称"></el-input>
        </el-form-item>
        <el-form-item label="任务类型">
          <el-select v-model="modifyRoleForm.jobType" placeholder="任务类型">
            <el-option label="定时-FIXTIME" value="FIXTIME"></el-option>
            <el-option label="实时-REALTIME" value="REALTIME"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态">
          <el-switch
            v-model="modifyRoleForm.status"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item prop="cron" v-if="modifyRoleForm.jobType === 'FIXTIME' || modifyRoleForm.jobType === ''" label="Cron表达式">
          <el-popover v-model="mcronPopover">
              <cron @change="changeMCron" @close="mcronPopover=false" i18n="cn"></cron>
              <el-input slot="reference" @click="mcronPopover=true" v-model="modifyRoleForm.cron" placeholder="请点击选择定时策略"></el-input>
          </el-popover>
        </el-form-item>
        <el-form-item v-if="modifyRoleForm.jobType === 'REALTIME'" label="Cron表达式">
          <el-input v-model="mTempCron" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item prop="beanName" label="任务执行类">
          <el-input v-model="modifyRoleForm.beanName" placeholder="任务执行类"></el-input>
        </el-form-item>
        <el-form-item label="任务参数">
          <el-input v-model="modifyRoleForm.jobParams" placeholder="任务参数"></el-input>
        </el-form-item>
        <el-form-item label="任务描述">
          <el-input
            style="font-size: 16px;"
            type="textarea"
            :rows="5"
            placeholder='请输入任务描述'
            v-model="modifyRoleForm.jobDesc">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitModifyItf">提交</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  import {cron} from 'vue-cron'
  export default {
    name: "List",
    props: {
    },
    data() {
      return {
        /*查询表单*/
        form: {
          name: ''
        },
        /*接口列表*/
        jobtableData: [],
        multipleSelection: [],
        /*分页*/
        curPage: 1,
        size: 5,
        total: 0,
        pages: 0,
        addItfVisible: false,
        addItfForm: {
          jobId: '',
          jobName: '',
          jobType: 'FIXTIME',
          jobDesc: '',
          beanName: '',
          groupId: 'GID001',
          jobParams: '',
          cron: '',
        },
        jobRules: {
          cron: [
            {required: true, message: 'CRON表达式不允许为空', trigger: 'blur'}
          ],
          beanName: [
            {required: true, message: '任务实现类不允许为空', trigger: 'blur'}
          ]
        },
        modifyRoleVisible: false,
        modifyRoleForm: {
          jobId: '',
          jobName: '',
          jobType: '',
          jobDesc: '',
          beanName: '',
          groupId: '',
          jobParams: '',
          cron: '',
          status: false
        },
        mJobRules: {
          cron: [
            {required: true, message: 'CRON表达式不允许为空', trigger: 'blur'}
          ],
          beanName: [
            {required: true, message: '任务实现类不允许为空', trigger: 'blur'}
          ]
        },
        cronPopover: false,
        mcronPopover: false,
        mTempCron: '* * * * * ? *',
        renderFunc(h, option) {
          return <span>{ option.key } - { option.label }</span>;
        },
      }
    },
    mounted: function(){
      this.queryJobList();
    },
    computed: {
      headers() {
        return {
          Authentication: this.$store.state.token,
          RefreshToken: this.$store.state.refresh_token
        };
      }
    },
    template: '<cron/>',
    components: { cron },
    methods: {
      changeCron(val){
        this.addItfForm.cron=val
      },
      changeMCron(val){
        this.modifyRoleForm.cron=val
      },
      clickAddItf(){
        this.addItfVisible = true;
        //加载新增对话框获取待新增的任务ID
        this.getJobId();
      },
      getJobId() {
        this.$http.post("/schedule/job/getJobId").then(resp => {
          if(resp.data.errCode === 200){
            this.addItfForm.jobId = resp.data.data;
          }
        })
      },
      handleSwithEnable(scope){
        this.$http.post("/role/info/isEnableRole", {
          "roleId": scope.row.roleId,
          "isEnabled": scope.row.enabled
        }).then(resp => {
          if(resp.data.errCode === 200){
            if(scope.row.enabled){
              this.$message.success("角色["+scope.row.roleName+"]已启用");
            }else{
              this.$message.success("角色["+scope.row.roleName+"]已停用");
            }
          }
        })
      },
      resetInterfaceQueryForm(form) {
        this.$refs[form].resetFields();
      },
      //接口查询
      onQuery(){
        this.queryJobList();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleResume(index, row) {
        console.log(index, row);
        this.resumeJob(row.jobId);
      },
      handlePause(index, row) {
        console.log(index, row);
        this.pauseJob(row.jobId);
      },
      handleEdit(index, row) {
        console.log(index, row);
        this.modifyItf(row.id);
      },
      handleDelete(index, row) {
        console.log(index, row);
        if(confirm("确认要删除？")){
          this.delItf(row.id);
        }
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.size = val;
        this.queryJobList();
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.curPage = val;
        this.queryJobList();
      },
      //提交新增接口
      addItf(){
        if(this.addItfForm.jobType === 'REALTIME'){
          this.addItfForm.cron = '* * * * * ? *';
        }
        this.$http.post("/schedule/job/add", this.addItfForm).then(resp => {
          if(resp.data.errCode === 200){
            this.$message.success("新增成功！");
            this.addItfVisible = false;
            this.queryJobList();
            this.clearAddItfForm();
          }
        });
        console.log("提交成功！");
      },
      //修改按钮(oprNum操作数为1时则为“修改”功能，否则为编辑)
      modifyItf(oprNum){
        //修改
        if(oprNum === 'modify'){
          //判断是否已选择
          if(this.multipleSelection.length !== 1){
            this.$message.error("请选择一条数据！");
            return;
          }
          this.modifyRoleVisible = true;
          this.multipleSelection.forEach(t => {
            this.queryOne(t.id);
          });
        }else { //编辑
          this.queryOne(oprNum);
        }
      },
      //删除
      delItf(oprNum){
        //删除按钮
        if(oprNum === 'del'){
          //判断是否已选择
          if(this.multipleSelection.length !== 1){
            this.$message.error("请至少选择一条数据！");
            return;
          }
          if(confirm("确认要删除？")){
            this.multipleSelection.forEach(t => {
              this.submitDelItf(t.id);
            });
          }
        }else { //操作中的删除
          this.submitDelItf(oprNum);
        }
      },

      //修改接口
      submitModifyItf(){
        if(this.modifyRoleForm.jobType === 'REALTIME'){
          this.modifyRoleForm.cron = '* * * * * ? *';
        }
        this.$http.post("/schedule/job/mod", {
          jobId: this.modifyRoleForm.jobId,
          jobName: this.modifyRoleForm.jobName,
          jobDesc: this.modifyRoleForm.jobDesc,
          jobType: this.modifyRoleForm.jobType,
          groupId: this.modifyRoleForm.groupId,
          beanName: this.modifyRoleForm.beanName,
          jobParams: this.modifyRoleForm.jobParams,
          cron: this.modifyRoleForm.cron,
          status: this.modifyRoleForm.status ? 'ON' : 'OFF',
        }).then(resp => {
          if(resp.data.errCode === 200){
            this.$message.success("接口修改成功！");
            this.modifyRoleVisible = false;
            this.queryJobList();
          }
        })
      },

      //导出接口数据
      outputItfData(){
        //判断是否已选择
        if(this.multipleSelection.length === 0){
          this.$message.error("请至少选择一条数据！");
          return;
        }
        this.$http({
          method: "post",
          url: "/mock/interface/export",
          data: this.multipleSelection,
          responseType: "blob"
        }).then(resp => {
          let url = window.URL.createObjectURL(new Blob([resp.data])); //创建blob,设置文件类型
          let a = document.createElement('a'); //创建a标签
          a.download = "接口数据表.xls"; //指定文件名
          a.style.display = 'none';
          a.href = url; //创建url
          a.click(); //click事件触发下载
          // URL.revokeObjectURL(a); //释放内存
        });
      },

      //查询接口列表
      queryJobList(){
        this.$http.post("/schedule/job/queryList", {
          "curPage": this.curPage,
          "size": this.size,
          "jobName": this.form.name
        }).then(resp => {
          if (resp.data.errCode === 200){
            console.log("query success!");
            this.jobtableData = resp.data.data.data;
            this.total = resp.data.data.totals;
            this.jobtableData.curPage = this.curPage;
          }
        })
      },

      //查询单个接口
      queryOne(id){
        this.$http.post("/schedule/job/query/"+id).then(resp => {
          if(resp.data.errCode === 200){
            this.modifyRoleVisible = true;
            this.modifyRoleForm.jobId = resp.data.data.jobId;
            this.modifyRoleForm.jobName = resp.data.data.jobName;
            this.modifyRoleForm.jobType = resp.data.data.jobType;
            this.modifyRoleForm.jobDesc = resp.data.data.jobDesc;
            this.modifyRoleForm.beanName = resp.data.data.beanName;
            this.modifyRoleForm.groupId = resp.data.data.groupId;
            this.modifyRoleForm.jobParams = resp.data.data.jobParams;
            this.modifyRoleForm.cron = resp.data.data.cron;
            this.modifyRoleForm.status = resp.data.data.status === 'ON';
          }
        })
      },

      //删除单个接口
      submitDelItf(id){
        this.$http.post("/schedule/job/delete/"+id).then(resp => {
          if(resp.data.errCode === 200){
            this.$message.success("删除成功！");
            this.queryJobList();
          }
        })
      },

      resumeJob(id){
        this.$http.post("/schedule/job/resumeJob/" + id, {}).then(resp =>{
          if(resp.data.errCode === 200){
            this.$message.success("任务[" + id + "]已成功恢复！");
            this.queryJobList();
          }
        })
      },

      pauseJob(id){
        this.$http.post("/schedule/job/pauseJob/" + id, {}).then(resp =>{
          if(resp.data.errCode === 200){
            this.$message.success("任务[" + id + "]已成功暂停！");
            this.queryJobList();
          }
        })
      },

      //清空查询条件
      clearQuery(){
        this.form = {
          name: ''
        }
      },
      clearAddItfForm(){
        this.addItfForm = {
          jobId: '',
          jobName: '',
          jobType: '',
          jobDesc: '',
          beanName: '',
          groupId: '',
          jobParams: '',
          cron: '',
        }
      },

    },

  }
</script>

<style scoped>
  .form-item{
    margin-left: 20px;
    width: 20%;
    display: inline-block;
  }
  .form-btn{
    position: relative;
    left: -60px;
  }
  .tag-btn{
    margin-left: 20px;
  }
  .interface-table{
    position: relative;
    left: 20px;
    top:10px;
  }
  .interpage{
    margin-top: 20px;
    margin-left: 20px;
    margin-bottom: 20px;
  }
  .curPageCounter{
    float: right;
    right: 40px;
  }
</style>
